;(function ($win, $doc) {
	apiready = function () {
		//初始化页面的方法
		api.setStatusBarStyle({
			style: 'dark'
		});
		if (api.winName === 'root' || api.winName === 'home') {
			_$.pageUnback();
		}
		if (api.winName !== 'root' && api.winName !== 'home') {
			var space = 0;
			$('#root').css({'padding': (api.safeArea.top + space) + 'px ' + (api.safeArea.right + space) + 'px ' + (api.safeArea.bottom + space) + 'px ' + (api.safeArea.left + space) + 'px'});
		}
		try {
			$('.app_head .back').on('click', function () {
				api.closeWin();
			})
			$('.app_head .search').on('click', function () {
				api.openWin({
					name: 'search',
					url: '../search/search.html',
					pageParam: {
						win: api.winName,
						frame: api.frameName
					}
				})
			})
			appready();
			api.parseTapmode();
		} catch (e) {
			if (__CONFIG__.runtime === 'dev') {
				alert('init err =>' + e);
			}
		}
		_$.debuger();
	};
	'use strict';
	var
		$delm = $doc.documentElement,
		//一些匿名占位的,多数是api插件，为了避免二次require;
		__browser__, __mediascanner__,
		//内置变量
		__debug__ = false,
		__helper__ = false,
		__libname__ = '_$',
		__rem__ = 20 / 750 * $delm.clientWidth,
		__udb__ = 'udb',
		__isAndroid__ = (/android/gi).test(navigator.appVersion),
		__storage__ = $win.localStorage,
		DAYTIME = 60 * 60 * 24 * 1000;
	//rem设置
	$win[__libname__] = {};
	$win[__libname__]['rem'] = __rem__;
	$delm.style.fontSize = $win[__libname__]['rem'] + 'px';
	//准备工作
	if (__isAndroid__) {
		try {
			__storage__ = os.localStorage()
		} catch (e) {
			console.log('__storage__ os error.' + e);
		}
	}
	if (__helper__) {
		console.log('template API \t' +
			'https://github.com/yanhaijing/template.js/blob/master/README.md');
	}
	//基础类定义
	var
		getType = function (o, _t, _e) {
			_e = ((_t = typeof(o)) == "object" ? o == null && "null" || Object.prototype.toString.call(o).slice(8, -1) : _t).toLowerCase();
			return _e;
		},
		tempid = function (num) {
			var n = getType(num) == 'number' ? num : 4;
			var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
			var res = "id_";
			for (var i = 0; i < n; i++) {
				var id = Math.ceil(Math.random() * 35);
				res += chars[id];
			}
			return res;
		},
		trim = function (str) {
			if (String.prototype.trim) {
				return str == null ? "" : String.prototype.trim.call(str);
			} else {
				return str.replace(/(^\s*)|(\s*$)/g, "");
			}
		},
		dataTest = function (k, v) {
			var regExps = {
				'code': "^\\d{6}$",//验证码
				'decmal': "^([+-]?)\\d*\\.\\d+$", //浮点数
				'intege': "^-?[1-9]\\d*$", //整数
				'num': "^([+-]?)\\d*\\.?\\d+$", //数字
				'num1': "^[1-9]\\d*|0$", //正数（正整数 + 0）
				'num2': "^-[1-9]\\d*|0$", //负数（负整数 + 0）
				'ascii': "^[\\x00-\\xFF]+$", //仅ACSII字符
				'chinese': "^[\\u4e00-\\u9fa5]+$", //仅中文
				'date': "^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期
				'year': "^\\d{4}$", //年份
				'month': "^(0?[[1-9]|1[0-2])$", //月份
				'day': "^(0?[[1-3]|1[0-9])$", //日子
				'email': "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件
				'idcard': "^[1-9]([0-9]{14}|[0-9]{17})$", //身份证
				'letter': "^[A-Za-z]+$", //字母
				'letter_l': "^[a-z]+$", //小写字母
				'letter_u': "^[A-Z]+$", //大写字母
				'mobile': "^0?(13|14|15|16|17|18|19)[0-9]{9}$", //手机
				'tel1': "^(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?$", //固定电话
				'notempty': "^\\S+$", //非空
				'password': "^.*[A-Za-z0-9\\w_-]+.*$", //密码
				'fullNumber': "^[0-9]+$", //数字
				'picture': "(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片
				'qq': "^[1-9]*[1-9][0-9]*$", //QQ号码
				'rar': "(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件
				'tel': "^[0-9\-()（）]{7,18}$", //电话号码的函数(包括验证国内区号,国际区号,分机号)
				'url': "^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url
				'username': "^[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+$", //用户名
				'zipcode': "^\\d{6}$", //邮编
				'realname': "^[A-Za-z\\u4e00-\\u9fa5]+$" // 真实姓名
			}
			var t = k in regExps ? regExps[k] : false;
			if (!k && !v) {
				return false;
			}
			var _v = trim(v, true);
			var regExpString = new RegExp(regExps[k]);
			if (__debug__) {
				console.log('dataTest : "' + _v + '"' + ' is ' + k + ' => ' + regExpString.test(_v));
			}
			return regExpString.test(_v);
		},
		sleep = function (call, time) {
			if (getType(time) !== 'number' && getType(call) !== 'function') {
				__debug__ && console.log('sleep(call, time) => 未指定call或者未指定time');
				return;
			}
			setTimeout(function () {
				call();
			}, time);
		},
		subStr = function (_str, _num, _do) {
			if (getType(_str) == 'string') {
				var num = getType(_num) == 'number' ? _num : 15,
					status = (_str.length > _num) ? (_do || '') : '';
				if (_str.length > num - 1) {
					_str = _str.substring(-1, num - 1) + status;
				}
				return _str;
			} else {
				console.log('subStrFun => arguments not is string');
			}
		},
		getDayTime = function (time, monthsDay) {
			var __dateTime,
				__data = {},
				__time = new Date(time),
				__date = new Date();
			__date.setFullYear(__time.getFullYear(), __time.getMonth(), __time.getDate());
			__date.setHours(0, 0, 0, 0);
			__dateTime = __date.getTime();
			__data.day_star = __dateTime;
			__data.day_end = __dateTime + DAYTIME - 1;
			__date.setDate(1);
			__dateTime = __date.getTime();
			__data.month_star = __dateTime;
			__data.month_end = __dateTime + DAYTIME * monthsDay - 1;
			__date.setMonth(11, 31);
			__dateTime = __date.getTime();
			__data.year_star = __dateTime;
			__data.year_end = __dateTime + DAYTIME - 1;
			return __data;
		},
		isLeapYear = function (year) {
			if (getType(year) !== 'number') {
				console.log('isLeapYear => year not is "number" !');
				return null;
			} else {
				return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
			}
		},
		getDifferDay = function (START, END, dayStar) {
			var dayStar = dayStar || 0,
				day = parseInt((END > START ? END - START : START - END ) / DAYTIME) + dayStar,
				week = parseInt(day / 7),
				weekDay = parseInt(day % 7);
			try {
				var _thisData = {
					day: day,
					week: week,
					weekDay: weekDay
				}
				if (__debug__) {
					console.log('getDifferDay START => ' + START);
					console.log('getDifferDay END => ' + END);
					console.log('getDifferDay dayStar => ' + dayStar);
					console.log('getDifferDay day => ' + _thisData);
				}
				return _thisData;
			} catch (e) {
				__debug__ && console.log('timer getDifferDay => ' + e);
			}
		},
		timeFormat = function (format, date) {
			/**
			 * 对日期进行格式化，
			 * @param date 要格式化的日期
			 * @param format 进行格式化的模式字符串
			 *     支持的模式字母有：
			 *     y:年,
			 *     M:年中的月份(1-12),
			 *     d:月份中的天(1-31),
			 *     h:小时(0-23),
			 *     m:分(0-59),
			 *     s:秒(0-59),
			 *     S:毫秒(0-999),
			 *     q:季度(1-4)
			 * @return String
			 */
			if (!date || !format) {
				return false;
			}
			date = new Date(date);
			var map = {
				"M": date.getMonth() + 1, //月份
				"d": date.getDate(), //日
				"h": date.getHours(), //小时
				"m": date.getMinutes(), //分
				"s": date.getSeconds(), //秒
				"q": Math.floor((date.getMonth() + 3) / 3), //季度
				"S": date.getMilliseconds(), //毫秒
				"D": date.getDay()//星期几
			};
			format = format.replace(/([yMdhmsqSD])+/g, function (all, t) {
				var v = map[t];
				if (v !== undefined) {
					if (all.length > 1) {
						v = '0' + v;
						v = v.substr(v.length - 2);
					}
					return v;
				}
				else if (t === 'y') {
					return (date.getFullYear() + '').substr(4 - all.length);
				}
				return all;
			});
			return format;
		},
		timer = function () {
			var time = arguments[0],
				__date = new Date(),//当前时间
				TIME = time;
			if (TIME && getType(TIME) !== 'number') {
				__debug__ && console.log('TIME not is number .');
				return false;
			} else if (!TIME) {
				TIME = __date.getTime();
			} else if (getType(TIME) !== 'date') {
				TIME = __date.setTime(TIME);
			} else {
				return __date;
			}
			var YEAR = __date.getFullYear() > 1900 ? __date.getFullYear() : __date.getFullYear() + 1900,
				MONTH = __date.getMonth(),
				DAY = __date.getDate(),
				WEEK = __date.getDay(),
				hh = __date.getHours(),
				mm = __date.getMinutes(),
				ss = __date.getSeconds(),
				ms = __date.getMilliseconds(),
				IS_LEAPYEAR = isLeapYear(YEAR),
				__data = {
					TIME: TIME,//毫秒数时间
					YY: YEAR < 1900 ? YEAR + 1900 : YEAR,//年
					MM: MONTH,//月
					DD: DAY,//日
					WEEK: WEEK,//周几
					MONTHS: [31, (IS_LEAPYEAR ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],//当年每月天数
					IS_LEAPYEAR: IS_LEAPYEAR,//是否是闰年
					hh: hh,//时
					mm: mm,//分
					ss: ss,//秒
					ms: ms,//毫秒
					//ms: ms,//毫秒
					TIMETEXT: [
						timeFormat('yyyy-MM', TIME),
						timeFormat('yyyy-MM-dd', TIME),
						timeFormat('hh:mm', TIME),
						timeFormat('hh:mm:ss', TIME)
					]
				};
			__data.MONTHSDAY = __data.MONTHS[__data.MM];
			__data.TIMESE = getDayTime(TIME, __data.MONTHSDAY);
			__debug__ && console.log(__data);
			return __data;
		},
		tpl = function (tpl, data) {
			var o = {
					sTag: '<%',
					eTag: '%>',
					compress: !__debug__,
					escape: true,
					error: function (e) {
						__debug__ && console.log(e);
					}
				},
				functionMap = {},
				modifierMap = {
					'': function (param) {
						return nothing(param)
					},
					'h': function (param) {
						return encodeHTML(param)
					},
					'u': function (param) {
						return encodeURI(param)
					},
					'subStr': function (str) {
						if (getType(str) === 'array') {
							return subStr(str[0], str[1], '...')
						} else {
							return subStr(str, 13, '...')
						}
					},
					'subStr16': function (str) {
						return subStr(str, 15, '...')
					},
					'date': function (number) {
						return timer(number).TIMETEXT[0]
					},
					'time': function (number) {
						return timer(number).TIMETEXT[3]
					},
					'jsonStr': function (json) {
						if (getType(json) !== 'object') {
							return json
						} else {
							return JSON.stringify(json);
						}
					},
					'getAreaName': function (id) {
						var name = false;
						__areaData__.directly.map(function (i) {
							if (i.id == id) {
								name = i.name;
							}
						})
						__areaData__.province.map(function (i) {
							if (i.id == id) {
								name = i.name;
							}
						})
						if (name !== false) {
							return name
						} else {
							return '未知地区'
						}
					},
					'getTop': function (idarr) {
						var classidName = 'top_',
							classes = '';
						if (idarr && idarr.length > 0) {
							for(var i =0;i<idarr.length;i++){
								if(idarr[i]!==0){
									classes+=classidName+i+' '
								}
							}
						}
						return classes;
					},
					'getDirection': function (idarr) {
						var classidName = 'direction_',
							classes = '';
						if (idarr && idarr.length > 0) {
							for(var i =0;i<idarr.length;i++){
								if(idarr[i]!==0){
									classes+=classidName+i+' '
								}
							}
						}
						return classes;
					},
					'getClassid': function (arr) {
						var classidName = '_classid_',
							classes = '';
						if (arr && arr.length > 0) {
							arr.map(function (i) {
								classes += classidName + i + ' '
							})
						}
						return classes;
					},
					'getClassifyName': function (id) {
						var name = false;
						try {
							__classifyData__.map(function (i) {
								if (i.id == id) {
									name = i.name;
								}
							})
						} catch (e) {
							_$.db.get({
								key: 'classify',
								call: function (data) {
									data.map(function (i) {
										if (i.id == id) {
											name = i.name;
										}
									})
								}
							})
						}
						if (name !== false) {
							return name
						} else {
							return '未找到'
						}
					}
				},
				toString = {}.toString,
				slice = [].slice;

			function type(x) {
				if (x === null) {
					return 'null';
				}
				var t = typeof x;
				if (t !== 'object') {
					return t;
				}
				var c = toString.call(x).slice(8, -1).toLowerCase();
				if (c !== 'object') {
					return c;
				}
				if (x.constructor == Object) {
					return c;
				}
				return 'unkonw';
			}

			function isObject(obj) {
				return type(obj) === 'object';
			}

			function isFunction(fn) {
				return type(fn) === 'function';
			}

			function isString(str) {
				return type(str) === 'string';
			}

			function extend() {
				var target = arguments[0] || {};
				var arrs = slice.call(arguments, 1);
				var len = arrs.length;
				for (var i = 0; i < len; i++) {
					var arr = arrs[i];
					for (var name in arr) {
						target[name] = arr[name];
					}
				}
				return target;
			}

			function clone() {
				var args = slice.call(arguments);
				return extend.apply(null, [{}].concat(args));
			}

			function nothing(param) {
				return param;
			}

			function encodeHTML(source) {
				return String(source)
					.replace(/&/g, '&amp;')
					.replace(/</g, '&lt;')
					.replace(/>/g, '&gt;')
					.replace(/\\/g, '&#92;')
					.replace(/"/g, '&quot;')
					.replace(/'/g, '&#39;');
			}

			function compress(html) {
				return html.replace(/\s+/g, ' ').replace(/<!--[\w\W]*?-->/g, '');
			}

			function consoleAdapter(cmd, msg) {
				typeof console !== 'undefined' && console[cmd] && console[cmd](msg);
			}

			function handelError(e) {
				var message = 'template.js error\n\n';
				for (var key in e) {
					message += '<' + key + '>\n' + e[key] + '\n\n';
				}
				message += '<message>\n' + e.message + '\n\n';
				consoleAdapter('error', message);
				o.error(e);
				function error() {
					return 'template.js error';
				}

				error.toString = function () {
					return '__code__ = "template.js error"';
				}
				return error;
			}

			function parse(tpl, opt) {
				var code = '';
				var sTag = opt.sTag;
				var eTag = opt.eTag;
				var escape = opt.escape;

				function parsehtml(line) {
					// 单双引号转义，换行符替换为空格
					line = line.replace(/('|")/g, '\\$1').replace(/\n/g, ' ');
					return ';__code__ += ("' + line + '")\n';
				}

				function parsejs(line) {
					//var reg = /^(:?)(.*?)=(.*)$/;
					var reg = /^(?:=|(:.*?)=)(.*)$/
					var html;
					var arr;
					var modifier;
					// = := :*=
					// :h=123 [':h=123', 'h', '123']
					if (arr = reg.exec(line)) {
						html = arr[2]; // 输出
						if (Boolean(arr[1])) {
							// :开头
							modifier = arr[1].slice(1);
						} else {
							// = 开头
							modifier = escape ? 'h' : '';
						}
						return ';__code__ += __modifierMap__["' + modifier + '"](typeof (' + html + ') !== "undefined" ? (' + html + ') : "")\n';
					}
					//原生js
					return ';' + line + '\n';
				}

				var tokens = tpl.split(sTag);
				for (var i = 0, len = tokens.length; i < len; i++) {
					var token = tokens[i].split(eTag);
					if (token.length === 1) {
						code += parsehtml(token[0]);
					} else {
						code += parsejs(token[0], true);
						if (token[1]) {
							code += parsehtml(token[1]);
						}
					}
				}
				return code;
			}

			function compiler(tpl, opt) {
				var mainCode = parse(tpl, opt);
				var headerCode = '\n' +
					'    var html = (function (__data__, __modifierMap__) {\n' +
					'        var __str__ = "", __code__ = "";\n' +
					'        for(var key in __data__) {\n' +
					'            __str__+=("var " + key + "=__data__[\'" + key + "\'];");\n' +
					'        }\n' +
					'        eval(__str__);\n\n';
				var footerCode = '\n' +
					'        ;return __code__;\n' +
					'    }(__data__, __modifierMap__));\n' +
					'    return html;\n';
				var code = headerCode + mainCode + footerCode;
				code = code.replace(/[\r]/g, ' '); // ie 7 8 会报错，不知道为什么
				try {
					var Render = new Function('__data__', '__modifierMap__', code);
					Render.toString = function () {
						return mainCode;
					}
					return Render;
				} catch (e) {
					e.temp = 'function anonymous(__data__, __modifierMap__) {' + code + '}';
					throw e;
				}
			}

			function compile(tpl, opt) {
				opt = clone(o, opt);
				try {
					var Render = compiler(tpl, opt);
				} catch (e) {
					e.name = 'CompileError';
					e.tpl = tpl;
					e.render = e.temp;
					delete e.temp;
					return handelError(e);
				}
				function render(data) {
					data = clone(functionMap, data);
					try {
						var html = Render(data, modifierMap);
						html = opt.compress ? compress(html) : html;
						return html;
					} catch (e) {
						e.name = 'RenderError';
						e.tpl = tpl;
						e.render = Render.toString();
						return handelError(e)();
					}
				}

				render.toString = function () {
					return Render.toString();
				};
				return render;
			}

			function template(tpl, data) {
				if (typeof tpl !== 'string') {
					return '';
				}
				var fn = compile(tpl);
				if (!isObject(data)) {
					return fn;
				}
				return fn(data);
			}

			template.config = function (option) {
				if (isObject(option)) {
					o = extend(o, option);
				}
				return clone(o);
			};
			template.registerFunction = function (name, fn) {
				if (!isString(name)) {
					return clone(functionMap);
				}
				if (!isFunction(fn)) {
					return functionMap[name];
				}
				return functionMap[name] = fn;
			}
			template.unregisterFunction = function (name) {
				if (!isString(name)) {
					return false;
				}
				delete functionMap[name];
				return true;
			}
			template.registerModifier = function (name, fn) {
				if (!isString(name)) {
					return clone(modifierMap);
				}
				if (!isFunction(fn)) {
					return modifierMap[name];
				}
				return modifierMap[name] = fn;
			}
			template.unregisterModifier = function (name) {
				if (!isString(name)) {
					return false;
				}
				delete modifierMap[name];
				return true;
			}
			template.__encodeHTML = encodeHTML;
			template.__compress = compress;
			template.__handelError = handelError;
			template.__compile = compile;
			template.version = '0.7.1';
			return template(tpl, data);
		},
		template = function (id, data, call) {

			if (!id || !data) {
				console.log('!id && !data');
				return;
			}
			call && call(tpl($doc.getElementById(id).innerHTML, data));

		},
		ajax = function (option) {
			if (getType(option) !== 'object') {
				__debug__ && console.error('ajax error => option not is object.');
				//option not is object;
				return false;
			}
			var
				//确定基础的ajax设置
				ajaxSetting = {
					encode: false,
					url: null,
					tag: null,
					method: 'post',
					cache: false,
					timeout: 4,
					dataType: 'json',
					charset: 'utf-8',
					headers: {},
					data: {
						values: null,
						files: {
							file: null
						}
					}
				},
				//确定ajax的url
				ajaxConfig;
			try {
				ajaxConfig = __CONFIG__[__CONFIG__.runtime].ajax;
				__CONFIG__.ajaxDebug && console.log('ajaxConfig' + JSON.stringify(ajaxConfig));
			} catch (e) {
				__CONFIG__.ajaxDebug && console.log('ajaxConfig error => ' + e);
				return false;
			}

			if (option.interface && option.interface in ajaxConfig.interface) {
				ajaxSetting.url = ajaxConfig.baseurl + ajaxConfig.interface[option.interface];
			} else {
				__CONFIG__.ajaxDebug && console.log('__CONFIG__ error => ajax url is null.');
				//没有url不执行ajax;
				return false;
			}
			//如果option中有data或者file，赋值给ajax设置
			if (getType(option.data) === 'object') {
				ajaxSetting.data.values = option.data;
			} else {
				ajaxSetting.data.values = {}
				__CONFIG__.ajaxDebug && console.log('ajax log [data] => data not is object. ignore ...');
			}
			if (getType(option.file) === 'array' || getType(option.file) === 'string') {
				ajaxSetting.data.files.file = option.file;
			} else {
				__CONFIG__.ajaxDebug && console.log('ajax log [file] => file not is array or string. ignore ...');
			}

			//尝试运行ajax请求
			try {
				__LODB__.get({
					call: function (data) {
						ajaxSetting.data.values.token = data.token;
						api.ajax(ajaxSetting, function (ret, err) {
							if (__CONFIG__.ajaxDebug) {
								console.log();
								console.log();
								console.log("╔══『 ajax 』════════════════════════════════════════╗");
								console.log('option => ' + JSON.stringify(option));
								console.log("══════════════════════════════════════════════════════");
								console.log('ajaxSetting => ' + JSON.stringify(ajaxSetting));
								console.log("══════════════════════════════════════════════════════");
								if (ret) {
									console.log('call.ret => ' + JSON.stringify(ret))
								}
								else {
									console.log('call.err => ' + JSON.stringify(err))
								}
								console.log("╚════════════════════════════════════════════════════╝");
								console.log();
								console.log();
							}
							if (getType(option.call) === 'function') {
								if (ret.status === 401) {
									api.toast({
										msg: '您还没有登录，请先登录'
									})
									getloginPage();
								} else {
									option.call(ret || err);
								}
							} else {
								__CONFIG__.ajaxDebug && console.log('ajax option.call not is function. ignore ...');
							}
						});
					}
				})
			} catch (e) {
				__CONFIG__.ajaxDebug && console.error('ajax error => ' + e);
			}
		},
		pageUnback = function () {
			api.addEventListener({
				name: 'keyback'
			}, function (ret, err) {
				api.closeWin({
					name: 'root'
				})
			});
			api.setWinAttr({
				slidBackEnabled: false
			});
		},
		widget = function (option) {
				__CONFIG__.debugLog && console.log(e)
		},
		loading={
			start:function(){
				$('#root').append('' +
					'<div class="app_mask animated fadeIn">' +
					//common_loading
					'<div class="common_loading"><img src="'+
					(api.wgtRootDir+'/lib/img/loading.gif')+
					'" alt="数据加载中"><span>数据加载中</span><span class="close_loading" onclick="$(\'.app_mask\').addClass(\'fadeOut\');_$.sleep(function(){$(\'.app_mask\').remove()},1500)"></span></div>' +
					'' +
					'</div>');
			},
			end:function(id){
				$('.app_mask').addClass('fadeOut');
				_$.sleep(function(){$(".app_mask").remove()},500);
			}
		},
		clipImg = function (pach, callName) {
			if (getType(pach) !== 'string' || getType(callName) !== 'string') {
				return false;
			}
			api.openWin({
				name: 'imageclip',
				url: '../page/imageclip.html',
				pageParam: {
					name: api.winName,
					pach: pach,
					callName: callName
				}
			});
		},
		imgCall = function (data, option) {
			if (getType(data) !== 'array' || data.length === 0) {
				api.toast({
					msg: '无有效的图片数据'
				})
				return;
			}
			var _list_ = data,
				_num = data.length,
				_data_ = [],
				mapFuns = function () {
					if (_list_.length > 0) {
						ajax({
							interface: 'imgUpload',
							data: {
								rfrom: option.rfrom || 'circle',
								num: _num
							},
							file: [_list_.shift()],
							call: function (data) {
								if (data.status === 200) {
									_data_.push(data.data[0]);
									mapFuns();
								} else {
									api.toast({
										msg: data.msg
									})
								}
							}
						})
					} else {
						console.log(JSON.stringify(_data_));
						option.call(_data_);
					}
				}
			mapFuns();
		},
		getCamera = function (option) {

			api.getPicture({
				sourceType: 'camera',
				encodingType: 'jpg',
				mediaValue: 'pic',
				destinationType: option.type ? option.type : 'url',
				allowEdit: false,
				quality: 60,
				targetWidth: 750,
				targetHeight: 750,
				saveToPhotoAlbum: false
			}, function (ret, err) {
				if (ret) {
					imgCall([ret.data], option);
				} else {
					api.toast({
						msg: err.message
					})
				}
			});
		},
		galleryImg = function (option) {

			__mediascanner__ = __mediascanner__ || api.require('UIMediaScanner');
			__mediascanner__.open({
				type: 'picture',
				column: 4,
				classify: true,
				max: option.max || 1,
				texts: {
					stateText: '已选*张',
					cancelText: '取消',
					finishText: '确认',
					selectedMaxText: '最多选择*张图片',
					classifyTitle: '选择图片'
				},
				styles: {
					bg: '#fff',
					mark: {
						icon: '',
						position: 'bottom_right',
						size: 20
					},
					nav: {
						bg: '#fff',
						stateColor: '#888',
						stateSize: 16,
						cancelBg: '#0099ff',
						cancelColor: '#888',
						cancelSize: 14,
						finishBg: '#0099ff',
						finishColor: '#fff',
						finishSize: 14
					}
				},
				exchange: true
			}, function (ret) {
				_$.sleep(function () {
					if (ret.eventType === 'confirm') {
						var _list_ = ret.list,
							_data_ = [],
							mapFuns = function () {
								if (_list_.length > 0) {
									__mediascanner__.transPath({
										path: _list_.shift().path
									}, function (ret) {
										if (ret) {
											_data_.push(ret.path);
										}
										mapFuns()
									});
								} else {
									imgCall(_data_, option);
								}
							}
						mapFuns();
					} else if (ret.eventType === 'cancel') {
						api.toast({
							msg: '取消了'
						})
					} else if (ret.eventType === 'albumError') {
						api.toast({
							msg: '请在设置中打开"艺考"的相册访问的权'
						})
					}
				}, 100)
			});
		},
		getImg = function (option) {
			/*
			 option={
			 max:1,
			 call:function
			 }
			 */
			api.actionSheet({
				cancelTitle: '取消',
				buttons: ['拍照', '相册']
			}, function (ret, err) {
				if (ret.buttonIndex == 1) {
					getCamera(option);
				} else if (ret.buttonIndex == 2) {
					galleryImg(option);
				} else {
					return;
				}
			});
		},
		viewImg = function (data) {
			var option = {
				name: 'img_view',
				url: '../page/view_img.html',
				delay: 150,
				bgColor: 'rgba(255,255,255,0)',
				pageParam: {
					img_data: data
				}
			}
			api.openWin(option);
		},
		__LODB__ = {
			'ext': function (option) {
				option.key = getType(option.key) === 'string' ? option.key : __udb__;
				__LODB__.get({
					key: option.key,
					call: function (_db_) {
						var v = option.val,
							vType = getType(v),
							dbType = getType(_db_);
						if (_db_ === '__unset__') {
							__LODB__.set(option);
						} else if ((vType === 'object' || vType === 'array') && (dbType === 'object' || dbType === 'array')) {
							option.val = _$.jsonExt(_db_, v);
							__LODB__.set(option);
						} else {
							__debug__ && console.log('__LODB__ ext error. Condition is not satisfied.');
						}
					}
				})
			},
			'set': function (option) {
				!__debug__ && console.log('__LODB__.set =>', JSON.stringify(option));
				if (getType(option) === 'object') {
					option.key = getType(option.key) === 'string' ? option.key : __udb__;
					var v = option.val,
						vType = getType(v);
					if (vType === 'object' || vType === 'array') {
						v = 'obj-' + JSON.stringify(v);
					} else if (vType === 'string') {
						v = 'str-' + v;
					} else if (vType === 'number') {
						v = 'num-' + v;
					} else if (vType === 'null') {
						v = 'nul-' + v;
					} else if (vType === 'boolean') {
						v = 'boo-' + v;
					} else if (vType === 'undefined') {
						v = 'und-' + v;
					}
					__storage__.setItem(option.key, v);
					getType(option.call) === 'function' && option.call(option.val, imgCache.default);
				} else {
					__debug__ && console.log('__LODB__ set error. option error.');
				}
			},
			'get': function (option) {
				__debug__ && console.log('__LODB__.get =>', JSON.stringify(option));
				if (getType(option) === 'object') {
					option.key = getType(option.key) === 'string' ? option.key : __udb__;
					var value = __storage__.getItem(option.key);
					if (!value) {
						if (option.key === __udb__) {
							alert('isudb');
							value = {
								token: null,
								type: 3,
								name: null,
								s_province: null,
								s_city: null,
								s_county: null,
								address: null,
								charge: null,
								phone: null,
								curriculum: null,
								propaganda: null,
								introduce: null,
								avatar: 'https://yikao.baolanbb.com/attachment/images/default/u_default.png',
								cover: null,
								qualifications: null,
								sex: null,
								age: null,
								school: null,
								m_school: null,
								c_points: null,
								addtime: null,
								integral: null
							}
						} else {
							value = '__unset__';
						}
					} else if (value.indexOf('obj-') === 0) {
						value = JSON.parse(value.slice(4));
					} else if (value.indexOf('str-') === 0) {
						value = value.slice(4);
					} else if (value.indexOf('nul-') === 0) {
						value = null;
					} else if (value.indexOf('num-') === 0) {
						value = parseFloat(value.slice(4));
					} else if (value.indexOf('boo-') === 0) {
						value = value.slice(4) === 'true' ? true : false;
					} else if (value.indexOf('und-') === 0) {
						value = undefined;
					}
					if (getType(option.call) === 'function') {
						option.call(value, imgCache.default);
					} else {
						return value;
					}
				} else {
					__debug__ && console.log('__LODB__ get error. option error.');
				}
			},
			'gets':function(option){
				var datas = []
				if (getType(option) === 'object' && getType(option.key) === 'array') {
					for (var i in option.key) {
						_$.db.get({
							key: option.key[i],
							call: function (data) {
								datas.push(data);
							}
						})
					}
				} else {
					__debug__ && console.log('__LODB__ gets error. option error.');
					return;
				}
				if (getType(option.call) === 'function') {
					option.call(datas);
				} else {
					return datas;
				}
			},
			'rm': function (option) {
				__debug__ && console.log('__LODB__.rm =>', JSON.stringify(option));
				if (getType(option) === 'object') {
					option.key = getType(option.key) === 'string' ? option.key : __udb__;
					__storage__.removeItem(option.key);
					getType(option.call) === 'function' && option.call();
				} else {
					__debug__ && console.log('__LODB__ rm error. option error.');
				}
			},
			'clear': function (option) {
				try {
					__debug__ && console.log('__LODB__.clear =>', option);
					__storage__.clear();
					getType(option.call) === 'function' && option.call();
				} catch (e) {
					__debug__ && console.log('__LODB__ clear error. ', e);
				}
			}
		},
		getloginPage = function () {
			api.execScript({
				name: 'index',
				script: "api.closeToWin({name:'index'});_$.sleep(function () {api.openWin({name:'user',url:'../user/user.html'})}, 750);"
			});
		},
		imgCache = {
			'default': '',
			'load': function (call) {
				//数据显示完成后调用此方法加载图片;
				var debug = false,
					imgs = $('img.imgcache').not('.imgcache_loading').addClass('imgcache_loading'),
					i = 0;
				debug && console.log('等待缓存的图片数量 => ' + imgs.length);
				function getCache() {
					var _i_ = $(imgs[i]);
					api.imageCache({
						'url': _i_.attr('data_src')
					}, function (ret, err) {
						debug && console.log(ret.status + ' => ' + ret.url);
						if (ret.status) {
							_i_.attr('src', ret.url).removeAttr('data_src').removeClass('imgcache imgcache_loading');
						} else if (!ret.status) {
							_i_.attr('src', ret.url);
							debug && console.log('imgCache(data,call) =>  imgCache load faild. use argument baseurl : ' + _i_.attr('data_src') + ' , err=> ' + err);
						}
						i++;
						if (i === imgs.length) {
							call && call();
						} else {
							getCache()
						}
					});
				}

				getCache();
			}
		};
	//集合输出
	$win[__libname__] = {
		getType: getType,
		loading:loading,
		tempid: tempid,
		pageUnback: pageUnback,
		subStr: subStr,
		trim: trim,
		dataTest: dataTest,
		sleep: sleep,
		timer: timer,
		jsonExt: function (_old, _new) {
			try {
				return $.extend({}, _old, _new);
			} catch (e) {
				__CONFIG__.debugLog && console.log(e);
				return false;
			}
		},
		ajax: ajax,
		widget: widget,
		template: template,
		img: {
			clip: clipImg,
			getImg: getImg,
			getCamera: getCamera,
			galleryImg: galleryImg,
			view: viewImg
		},
		db: __LODB__,
		imgCache: imgCache,
		sendComment: function (name, title, mid, data) {
			if(__debug__){
				console.log('============================');
				console.log(JSON.stringify(data));
				console.log('============================');
			}
			api.openWin({
				name: 'commentWin',
				url: '../search/comment.html',
				animation: 'curl',
				pageParam: {
					mid: mid,
					act: name,
					actName: title,
					data: data,
					content: '',
					imgs: null,
					classify: null,
					actWin: api.winName,
					actFrame: api.frameName,
					call: name + '_ajaxCall'
				}
			})
		},
		debuger: function () {
			try {
				api.addEventListener({
					name: 'longpress'
				}, function () {
					api.actionSheet({
						title: '开发调试菜单',
						cancelTitle: '取消',
						buttons: ['清除DB', '清除缓存', 'UDB', '重启应用', '刷新', '测试页面']
					}, function (ret, err) {
						switch (ret.buttonIndex) {
							case 1: {
								__LODB__.clear({
									call: function () {
										api.toast({
											msg: '清除DB'
										});
									}
								});
								break;
							}
							case 2: {
								api.clearCache(function () {
									api.toast({
										msg: '清除了缓存'
									});
								});
								break;
							}
							case 3: {
								console.log("╔══『 _$.db 』════════════════════════════════════════╗")
								__LODB__.get({
									call: function (data) {
										console.log(JSON.stringify(data));
									}
								})
								console.log("╚════════════════════════════════════════════════════╝")
								break;
							}
							case 4: {
								api.rebootApp();
								break;
							}
							case 5: {
								window.location.reload();
								break;
							}
							case 6: {
								api.openWin({
									name: 'test',
									url: '../root/test.html'
								});
								break;
							}
						}
					});
				});
			} catch (e) {
				$win.api = {
					safeArea: {
						top: 40,
						left: 0,
						bottom: 21,
						right: 0
					},
					removeLaunchView: function () {
						console.log('removeLaunchView');
					},
					setPrefs: function () {
						console.log('setPrefs');
					},
					openWin: function (option) {
						$win.location.href = option.url;
					}
				}
				$('#root').on('click', function () {
					console.log('reload page...');
					window.location.reload()
				});
			}
		},
		viewArtcircle: function (obj, mid,self) {
			var data = __LODB__.get({key: __udb__});
			if ((data.type !== 1 && data.type !== 2) || data.token===null) {
				api.toast({
					msg: '请先登录并选择身份'
				})
				getloginPage();
				return false;
			} else {
				api.openWin({
					name: 'viewArtcircle',
					url: '../artcircle/artcircle_view.html',
					pageParam: {
						actWin: api.winName,
						actFrame: api.frameName,
						mid: mid,
						isSelf:self
					}
				});
			}
		},
		viewClassIntro: function (obj, id) {
			var data = __LODB__.get({key: __udb__});
			if ((data.type !== 1 && data.type !== 2) || data.token===null) {
				api.toast({
					msg: '请先登录并选择身份'
				})
				getloginPage();
				return false;
			} else {
				api.openWin({
					name:'mechanism_class_view',
					url:'../mechanism/mechanism_class_view.html',
					pageParam:{
						id:id
					}
				})
			}
		},
		getView: function (act, id, obj) {
			var data = __LODB__.get({key: __udb__});
			if ((data.type !== 1 && data.type !== 2) || data.token===null) {
				api.toast({
					msg: '请先登录并选择身份'
				})
				getloginPage();
				return false;
			} else {
				if (!act || !id) {
					return
				} else {
					if (act === 'class') {
						api.openWin({
							name: 'classroom_view',
							url: '../classroom/classroom_view.html',
							pageParam: {
								id: id
							}
						})
					}
					if (act === 'mechanism') {
						api.openWin({
							name: 'mechanism',
							url: '../mechanism/mechanism_view.html',
							pageParam: {
								id: id
							}
						})
					}
				}
			}
		},
		getPage: function (url) {
			if (!url) {
				console.log('!url');
				return false;
			}
			__browser__ = __browser__ || api.require('webBrowser');
			var data = __LODB__.get({key: __udb__});
			if ((data.type !== 1 && data.type !== 2) || data.token===null) {
				api.toast({
					msg: '请先登录并选择身份'
				})
				getloginPage();
				return false;
			} else {
				__browser__.open({
					url: url,
					progress: {
						color: '#0099ff'
					}
				});
			}

		}
	};
})(window, document);